//
//  UserFinanceChartViewController.m
//  XinKaiFa55like
//
//  Created by junseek on 2017/3/24.
//  Copyright © 2017年 55like lj. All rights reserved.
//

#import "UserFinanceChartViewController.h"
#import "PNLineChart.h"
#import "PNLineChartData.h"
#import "PNLineChartDataItem.h"
#import "NavigationBarToggleTabView.h"

@interface UserFinanceChartViewController ()<PNChartDelegate>{
    UIScrollView *scrollViewBG;
    UIScrollView *scrollChartBG;
    
    UILabel *lblTop1;
    UILabel *lblTop2;
    
    UIView *viewLineChart;
    PNLineChart *lineChart;
    
    
    UILabel *lblB1;
    UILabel *lblB2;
    
    
    UILabel *lblMoney1;
    UILabel *lblMoney2;
    
    NSString *strTempCid;
    NSDictionary *dicChartData;
}

@end

@implementation UserFinanceChartViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self navbarTitle:@" "];
    self.backButton.frameWidth=60;
    [self initComponents];
    [self initNavTopButtons];
}
-(void)initNavTopButtons{
    NavigationBarToggleTabView *toggleTab=[[NavigationBarToggleTabView alloc] initWithFrame:CGRectMake((kScreenWidth-225)/2, 28, 225, 28)];
    [self.navView addSubview:toggleTab];
    [toggleTab setTiltelArray:@[@{@"title":@"业绩",@"id":@"1"},@{@"title":@"支出",@"id":@"2"},@{@"title":@"利润",@"id":@"3"}] toggleTab:^(NSDictionary *dicSelect) {
        strTempCid=[dicSelect valueForJSONStrKey:@"id"];
        lblB1.text=[NSString stringWithFormat:@"个人%@",[dicSelect valueForJSONStrKey:@"title"]];
        lblTop1.text=[NSString stringWithFormat:@"个人%@",[dicSelect valueForJSONStrKey:@"title"]];
        lblB2.text=[NSString stringWithFormat:@"公司平均%@",[dicSelect valueForJSONStrKey:@"title"]];
        lblTop2.text=[NSString stringWithFormat:@"公司平均%@",[dicSelect valueForJSONStrKey:@"title"]];
        [self refreshMyamoebaData];
    }];
}

- (void)initComponents{
    scrollViewBG=[[UIScrollView alloc] initWithFrame:CGRectMake(0, kTopHeight, kScreenWidth, kContentHeight)];
    [self.view addSubview:scrollViewBG];
    UIView *bgV=[[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 10)];
    bgV.backgroundColor=[UIColor whiteColor];
    [scrollViewBG addSubview:bgV];
    
    [scrollViewBG addSubview:[RHMethods labelWithFrame:CGRectMake(0, 10, kScreenWidth, 25) font:fontTitle color:rgbTitleColor text:@"阿米巴曲线图" textAlignment:NSTextAlignmentCenter]];
    
    UIView *viewRedT=[RHMethods lineViewWithFrame:CGRectMake(10, 45, 10, 8)];
    viewRedT.backgroundColor=[UIColor redColor];
    [scrollViewBG addSubview:viewRedT];
    lblTop1=[RHMethods labelWithFrame:CGRectMake(25, 40, 100, 18) font:fontSmallTitle color:[UIColor redColor] text:@"个人利润"];
    [scrollViewBG addSubview:lblTop1];
    
    UIView *viewGreenT=[RHMethods lineViewWithFrame:CGRectMake(10, 65, 10, 8)];
    viewGreenT.backgroundColor=RGBCOLOR(0, 165, 99);
    [scrollViewBG addSubview:viewGreenT];
    lblTop2=[RHMethods labelWithFrame:CGRectMake(25, 60, 100, 18) font:fontSmallTitle color:RGBCOLOR(0, 165, 99) text:@"公司平均利润"];
    [scrollViewBG addSubview:lblTop2];

    
    scrollChartBG=[[UIScrollView alloc] initWithFrame:CGRectMake(0, YH(lblTop1)+15, kScreenWidth, 250)];
    scrollChartBG.backgroundColor=[UIColor clearColor];
    [scrollViewBG addSubview:scrollChartBG];
    
    [scrollViewBG addSubview:[RHMethods lineViewWithFrame:CGRectMake(0, YH(scrollChartBG), kScreenWidth, 0.5)]];
    [scrollViewBG addSubview:[RHMethods lineViewWithFrame:CGRectMake(kScreenWidth/2, YH(scrollChartBG), 0.5, 80)]];
    [scrollViewBG addSubview:[RHMethods lineViewWithFrame:CGRectMake(0, YH(scrollChartBG)+79.5, kScreenWidth, 0.5)]];
    
    float fty=YH(scrollChartBG);
    
    lblB1=[RHMethods labelWithFrame:CGRectMake(0, fty+10, kScreenWidth/2, 25) font:fontSmallTitle color:rgbTxtDeepGray text:@"个人利润" textAlignment:NSTextAlignmentCenter];
    [scrollViewBG addSubview:lblB1];
    
    lblB2=[RHMethods labelWithFrame:CGRectMake( kScreenWidth/2, fty+10, kScreenWidth/2, 25) font:fontSmallTitle color:rgbTxtDeepGray text:@"公司平均利润" textAlignment:NSTextAlignmentCenter];
    [scrollViewBG addSubview:lblB2];

    lblMoney1=[RHMethods labelWithFrame:CGRectMake(0, fty+30, kScreenWidth/2, 40) font:BoldFont(35) color:[UIColor redColor] text:@"" textAlignment:NSTextAlignmentCenter];
    [scrollViewBG addSubview:lblMoney1];
  
    lblMoney2=[RHMethods labelWithFrame:CGRectMake( kScreenWidth/2, fty+30, kScreenWidth/2, 40) font:BoldFont(35) color:RGBCOLOR(0, 165, 99) text:@"" textAlignment:NSTextAlignmentCenter];
    [scrollViewBG addSubview:lblMoney2];
   
    
    bgV.frameHeight=fty+80;
    float fh=YH(bgV)+20>H(scrollViewBG)+1?YH(bgV)+20:H(scrollViewBG)+1;
    [scrollViewBG setContentSize:CGSizeMake(W(scrollViewBG)-1, fh)];
    
    
}
///获取数据
-(void)refreshMyamoebaData{
    //
    krequestParam
    [dictparam setValue:@"2" forKey:@"type"];//（1 个人按月排行  2曲线图）默认显示1
    [dictparam setValue:strTempCid forKey:@"cid"];
    [NetEngine createGetAction_LJ_two:[NSString stringWithFormat:@"%@%@",XKFV3usermyamoeba,dictparam.wgetParamStr] onCompletion:^(id resData, BOOL isCache) {
        if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"200"]) {
            dicChartData=[resData objectForJSONKey:@"data"];
            [self refreshBarChart];
        }else{
            [SVProgressHUD showImage:nil status:[resData valueForJSONStrKey:@"info"]];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [super backButtonClicked:nil];
            });
        }
    } onError:^(NSError *error) {
        [SVProgressHUD showImage:nil status:alertErrorTxt];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [super backButtonClicked:nil];
        });
    }];
    
}

////刷新图表
-(void)refreshBarChart{
    for (UIView *vt in [scrollChartBG subviews]) {
        [vt removeFromSuperview];
    }
    
    viewLineChart=[RHMethods lineViewWithFrame:CGRectMake(0, 0, 30, H(scrollChartBG)-50)];
    viewLineChart.backgroundColor=RGBACOLOR(229, 166,  61, 0.5);
    [scrollChartBG addSubview:viewLineChart];
    //图表
    NSMutableArray *arrayTitle=[NSMutableArray new];
    NSMutableArray *arrayValue=[NSMutableArray new];
    NSMutableArray *arrayMValue=[NSMutableArray new];//个人
  //  NSMutableArray *arraydeal=[[NSMutableArray alloc] init];
  
    for (int i=0;i<[[dicChartData objectForJSONKey:@"list"] count];i++) {
        NSDictionary *dic = [[dicChartData objectForJSONKey:@"list"] objectAtIndex:i];
        if ([[dic valueForJSONStrKey:@"companyfund"] notEmptyOrNull]) {
            [arrayValue addObject:[dic valueForJSONStrKey:@"companyfund"]];
        }else{
            [arrayValue addObject:@"0"];
        }
        if ([[dic valueForJSONStrKey:@"fund"] notEmptyOrNull]) {
            [arrayMValue addObject:[dic valueForJSONStrKey:@"fund"]];
        }else{
            [arrayMValue addObject:@"0"];
        }
        
        [arrayTitle addObject:[NSString stringWithFormat:@"%@月",[dic valueForJSONStrKey:@"ctime"]]];
    }
    CGFloat max_value = [[arrayValue valueForKeyPath:@"@max.floatValue"] floatValue];  //最大值
    CGFloat min_value = [[arrayValue valueForKeyPath:@"@min.floatValue"] floatValue];  //最小值
    
    CGFloat max_value2 = [[arrayMValue valueForKeyPath:@"@max.floatValue"] floatValue];  //最大值
    CGFloat min_value2 = [[arrayMValue valueForKeyPath:@"@min.floatValue"] floatValue];  //最小值
    
    float lfChartW=40;
    float ftChart_w=[arrayTitle count] * lfChartW +100;
    
    if ([arrayTitle count]<=7 || ftChart_w<kScreenWidth) {
        ftChart_w=kScreenWidth;
    }
    
    lineChart = [[PNLineChart alloc] initWithFrame:CGRectMake(0, 0, ftChart_w, H(scrollChartBG))];
    //    lineChart.yLabelFormat = @"%1.1f";
    lineChart.backgroundColor = [UIColor clearColor];
    [lineChart setXLabels:arrayTitle];
    lineChart.showCoordinateAxis = YES;
    
    //Use yFixedValueMax and yFixedValueMin to Fix the Max and Min Y Value
    //Only if you needed
    
    lineChart.yLabelFormat = @"%1.2f";
    lineChart.yFixedValueMax = max_value>max_value2?max_value:max_value2;//[[dicAlldata valueForJSONStrKey:@"maxSell"] floatValue];
    lineChart.yFixedValueMin = min_value<min_value2?min_value:min_value2;//[[dicAlldata valueForJSONStrKey:@"minSell"] floatValue];
    //个人利润
    // Line Chart #1
    NSArray * data01Array = arrayMValue;//个人利润
    PNLineChartData *data01 = [PNLineChartData new];
    data01.dataTitle = @"Alpha";
    data01.color = [UIColor redColor];
    //        data01.alpha = 0.3f;
    data01.itemCount = data01Array.count;
    data01.inflexionPointWidth=4;
    data01.lineWidth=0.5;
    data01.inflexionPointStyle = PNLineChartPointStylePoint;
    
    
    data01.getData = ^(NSUInteger index) {
        CGFloat yValue = [data01Array[index] floatValue];
        return [PNLineChartDataItem dataItemWithY:yValue];
    };
    
    // Line Chart #2
    NSArray * data02Array =arrayValue;//公司平均
    PNLineChartData *data02 = [PNLineChartData new];
    data02.dataTitle = @"Beta Beta Beta Beta";
    data02.color = RGBCOLOR(0, 165, 99);
    //        data02.alpha = 0.5f;
    data02.itemCount = data02Array.count;
    data02.inflexionPointWidth=4;
    data02.lineWidth=0.5;
    data02.inflexionPointStyle = PNLineChartPointStylePoint;
    
    
    data02.getData = ^(NSUInteger index) {
        CGFloat yValue = [data02Array[index] floatValue];
        return [PNLineChartDataItem dataItemWithY:yValue];
    };
    
    lineChart.chartData = @[data01,data02];//
   
    
    [lineChart strokeChart];
    lineChart.delegate = self;
    
    [scrollChartBG addSubview:lineChart];
    
    [scrollChartBG setContentSize:CGSizeMake(W(lineChart), H(scrollChartBG)-1)];
    [scrollChartBG setContentOffset:CGPointMake(W(lineChart)-W(scrollChartBG), 0)];
    
    
    [self refreshSelectChartPoint:[arrayTitle count]-1];
    
}
-(void)refreshSelectChartPoint:(NSInteger)index{
    UILabel *lblTitle=[lineChart viewWithTag:index+10];
    DLog(@"cy:%f",lblTitle.center.x);
    viewLineChart.center=CGPointMake(lblTitle.center.x, viewLineChart.center.y);
    
    NSDictionary *dic = [[dicChartData objectForJSONKey:@"list"] objectAtIndex:index];
    lblMoney1.text=[NSString stringWithFormat:@"%.2f万元",[[dic valueForJSONStrKey:@"fund"] floatValue]];
    lblMoney2.text=[NSString stringWithFormat:@"%.2f万元",[[dic valueForJSONStrKey:@"companyfund"] floatValue]];
    
    NSInteger lengthT=@"万元".length;
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:lblMoney1.text];
    [str addAttribute:NSFontAttributeName value:fontSmallTitle range:NSMakeRange(lblMoney1.text.length-lengthT, lengthT)];
    lblMoney1.attributedText = str;
    
    NSInteger lengthT2=@"万元".length;
    NSMutableAttributedString *str2 = [[NSMutableAttributedString alloc] initWithString:lblMoney2.text];
    [str2 addAttribute:NSFontAttributeName value:fontSmallTitle range:NSMakeRange(lblMoney2.text.length-lengthT2, lengthT2)];
    lblMoney2.attributedText = str2;
    
}

#pragma mark PNChartDelegate
- (void)userClickedOnLineKeyPoint:(CGPoint)point lineIndex:(NSInteger)lineIndex pointIndex:(NSInteger)pointIndex{
    DLog(@"Click Key on line %f, %f line index is %d and point index is %d",point.x, point.y,(int)lineIndex, (int)pointIndex);
    
    [self refreshSelectChartPoint:pointIndex];
}

- (void)userClickedOnLinePoint:(CGPoint)point lineIndex:(NSInteger)lineIndex{
    DLog(@"Click on line %f, %f, line index is %d",point.x, point.y, (int)lineIndex);
}

-(void)userClickedOnXLableIndex:(NSInteger)index{
    DLog(@"Click on Lable Index:%ld",index)
    [self refreshSelectChartPoint:index];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
